package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {


    /**
     * 获取静态资源绝对路径
     *
     * @param url
     * @return
     */
    public static String getAbsolutePath(String url) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + url;
    }

    /**
     * 读取静态资源文件,通过IO流输出
     *
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {

        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        int resourceSize = count; //静态资源文件总长度
        //先输出 http 请求头,在输出响应内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        //定义 参数 用于io流读写
        long written = 0; //已经读取的长度
        int byteSize = 1024; //每次读取的长度
        byte[] bytes = new byte[byteSize];

        while (written < resourceSize) {//当已经读取的文件长度 小于总文件长度时 继续读写
            //判断 当已经读取的长度加上1024字节 大于文件总长度时 应该读取的直接= 文件总长度-已经读取的长度
            if (written + byteSize > resourceSize) {
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written+=byteSize;
        }


    }


}
